import { DATE_TIME_FORMAT } from '@/constants';
import type { PageInfo, PageResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useModel, useNavigate } from 'alita';
import {
  Button,
  Grid,
  InfiniteScroll,
  List,
  SearchBar,
  Space,
} from 'antd-mobile';
import type { SearchBarRef } from 'antd-mobile/es/components/search-bar';
import dayjs from 'dayjs';
import { useEffect, useRef, useState,FC } from 'react';
import { type OADepartment  } from '../typing';
import { type DetailResult } from '@/pages/types/type';
import styles from './index.less';
//如果@/pages/types/type中定义的OADepartment不合适，且无法更改，可以在这里重新定义一个。
// interface OADepartment {
//     id: number,
//     name: string //Response未COPY出来，无字段定义！
//     fullName: string,
//     weiXinId: number,
//     createdAt: string,
//     creator: WeiXinUser,
//     leader?: WeiXinUser,
//     modifier: WeiXinUser,
//     updatedAt: string,
// }

const InitButton: FC<{ onSuccess: () => void }> = ({ onSuccess }) => {
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(2);
  const [count,setCount] = useState<number>(1);

  useEffect(() => {
    console.log('正在查找部门有多少个');
    let times = 1;
    const typeOptionsUrl = `/api/oa-department-rel/get-total-count`; // 生成代码搜索位置：2492-0412-5263-8850-4512-8512-3502
    fetch(`${urlPrefix}${typeOptionsUrl}`, getRequestInit()) 
      .then(async (rsp: Response) => {
        // fetch返回类型： Promise<Response>
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }:  DetailResult<number>) => {
              if (code === 0) {
                setLoadOK(msg);
                setCount(data!);
              } else {
                setLoadFails([...loadFails, msg]);
              }
            })
            .catch((reason) => {
              setLoadFails([...loadFails, reason]);
            })
            .finally(() => {
              console.log(`${typeOptionsUrl} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFails([
          ...loadFails,
          `请求${typeOptionsUrl}时发生错误：${reason}`,
        ]);
      })
      .finally(() => {
        console.log(`${typeOptionsUrl} outter finally!`);
        setLoadingTimes(--times);
      });
  }, []);

  function initOADepartment(){
    console.log('正在从钉钉中初始化部门');
    let times = 1;
    const typeOptionsUrl = `/api/qywx-sass-department/get-all-simplelist`; // 生成代码搜索位置：2492-0412-5263-8850-4512-8512-3502
    fetch(`${urlPrefix}${typeOptionsUrl}`, getRequestInit()) 
      .then(async (rsp: Response) => {
        // fetch返回类型： Promise<Response>
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({  code, msg }:  DetailResult<any>) => {
              if (code === 0) {
                setLoadOK(msg);
                onSuccess();
              } else {
                setLoadFails([...loadFails, msg]);
              }
            })
            .catch((reason) => {
              setLoadFails([...loadFails, reason]);
            })
            .finally(() => {
              console.log(`${typeOptionsUrl} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFails([
          ...loadFails,
          `请求${typeOptionsUrl}时发生错误：${reason}`,
        ]);
      })
      .finally(() => {
        console.log(`${typeOptionsUrl} outter finally!`);
        setLoadingTimes(--times);
      });
  }

  return <Button onClick={initOADepartment} disabled={loadingTimes>0} loading={loadingTimes>0} size={'mini'}>初始化({count})</Button>;
};

export default () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [pageInfo, setPageInfo] = useState<PageInfo>({
    totalPages: 0,
    page: 0,
    size: 15,
    code: 0,
    msg: '未搜索',
    totalElements: -1,
    last: false,
  });
  const [data, setData] = useState<OADepartment[]>([]);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [tokening, setTokening] = useState<boolean>(false);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadingTimes, setLoadingTimes] = useState<number>(1);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const searchRef = useRef<SearchBarRef>(null);
  const model = useModel('useAuthModel');
  async function doSearch(
    name: string | undefined = undefined,
    page: number = 0,
  ): Promise<PageResult<OADepartment>> {
    try {
      //下面可以需要添加一些默认参数！
      const rsp: Response = await fetch(
        `${urlPrefix}/api/oa-department-search`,
        postRequestInit({ name, size: 15, page }),
      ); // RequestInit
      if (rsp.ok) {
        return rsp.json();
      } else {
        return Promise.reject({ code: rsp.status, msg: rsp.statusText });
      }
    } catch (e) {
      return Promise.reject({ code: 1400, msg: `请求异常${e}` });
    }
  }
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: { hideNavBar: true, pageTitle: '部门' },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);
  function load() {
    if (authOK) {
      let times = 1;
      doSearch()
        .then((rsp: PageResult<OADepartment>) => {
          const {
            data,
            code,
            msg,
            page,
            size,
            totalElements,
            totalPages,
            last,
          } = rsp;
          if (code === 0) {
            setData(data!);
            setPageInfo({
              code,
              msg,
              page,
              size,
              totalElements,
              totalPages,
              last,
            });
            setLoadOK(msg);
            setHasMore(!last);
          } else {
            setData([]);
            setLoadFails([...loadFails, msg]);
            setHasMore(false);
          }
        })
        .catch((reason) => {
          setLoadFails([...loadFails, reason]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    }
  }
  useEffect(load, [authOK]);
  async function search(val: string | undefined) {
    console.log('searching...');
    doSearch(val, 0)
      .then((rsp: PageResult<OADepartment>) => {
        const { data, code, msg, page, size, totalElements, totalPages, last } =
          rsp;
        if (code === 0) {
          setData(data!);
          setPageInfo({
            code,
            msg,
            page,
            size,
            totalElements,
            totalPages,
            last,
          });
          setHasMore(!last);
        } else {
          setData([]);
          setLoadFails([...loadFails, msg]);
          setHasMore(false);
        }
      })
      .catch((reason) => {
        setLoadFails([...loadFails, reason]);
      })
      .finally(() => {
        console.log('searching complete!');
      });
  }
  async function loadMore() {
    console.log('loading more...');
    const rsp = await doSearch(
      searchRef.current?.nativeElement?.value,
      pageInfo.page + 1,
    );
    const { data, code, msg, page, size, totalElements, totalPages, last } =
      rsp;
    if (code === 0) {
      setData((currents) => [...currents, ...data!]);
      setPageInfo({ code, msg, page, size, totalElements, totalPages, last });
      setLoadOK(msg);
      setHasMore(!last);
    } else {
      setData([]);
      setLoadFails([...loadFails, msg]);
      setHasMore(false);
    }
  }
  if (tokening) {
    return <h3>正在登录...</h3>;
  }
  if (loadingTimes > 0) {
    return <h3>正在加载...</h3>;
  }
  return (
    <Page>
      <Content>
        <div className={styles.header}>
          <div className={styles.left}>
            <SearchBar
              ref={searchRef}
              onSearch={(val: string) => {
                search(val);
              }}
            />
          </div>
          <div className={styles.right}>
            <Button
              size="small"
              color="primary"
              onClick={() => {
                const val = searchRef.current?.nativeElement?.value;
                console.log(
                  'nativeElement.value=',
                  searchRef.current?.nativeElement?.value,
                );
                search(val);
              }}
            >
              {' '}
              搜索({pageInfo.totalElements})
            </Button>
            <InitButton onSuccess={load}  />
          </div>
        </div>
        <div className={styles.oaDepartmentList}>
          <List>
            {data.map(
              ({ id, fullName, creator, createdAt, weiXinId, leader }) => (
                <List.Item
                  key={id}
                  description={
                    <>
                      <Grid columns={1} gap={8} style={{ marginTop: '8px' }}>
                        <Grid.Item span={1}>
                          <Space wrap>
                            负责人：{leader?.name || '无负责人'}
                          </Space>
                        </Grid.Item>
                      </Grid>
                      <Grid columns={1} gap={8} style={{ marginTop: '8px' }}>
                        <Grid.Item span={1}>
                          <Space wrap>创建人：{creator.name}</Space>
                        </Grid.Item>
                      </Grid>
                      <Grid columns={1} gap={8} style={{ marginTop: '8px' }}>
                        <Grid.Item>
                          <Space wrap>
                            创建时间:{dayjs(createdAt).format(DATE_TIME_FORMAT)}
                          </Space>
                        </Grid.Item>
                      </Grid>
                      <Grid columns={2} gap={8} style={{ marginTop: '8px' }}>
                        <Grid.Item>
                          <Space wrap>内码：{id}</Space>
                        </Grid.Item>
                        <Grid.Item>
                          <Space wrap>企业微信ID：{weiXinId}</Space>
                        </Grid.Item>
                      </Grid>
                    </>
                  }
                  onClick={() => {
                    navigate(`/backend/oa-department/detail?id=${id}`);
                  }}
                >
                  {fullName}
                </List.Item>
              ),
            )}
          </List>
        </div>
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={hasMore}
          threshold={0}
        ></InfiniteScroll>
      </Content>{' '}
    </Page>
  );
};
